package com.guigu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.guigu.bean.Life;
import com.guigu.bean.Msg;
import com.guigu.service.LifeServices;

/**
 * @author 执子一白
 *控制生活日记的CRUD请求
 */
@Controller
public class LifeController {

	@Autowired
	LifeServices lifeServices;
	
	
	/**
	 * 查询生活函数
	 * @param vagueDate
	 * @param userId
	 * @return 返回json数据
	 */
	@RequestMapping("/findlifes")
	@ResponseBody
	public Msg getLifesByVagueDate(String vagueDate,@RequestParam(defaultValue="0")int userId){
		List<Life> lifes =lifeServices.getLifesByVagueDate(vagueDate, userId);
		if (lifes!=null&&!lifes.isEmpty()) {
			return Msg.success().add("lifes", lifes);
		}else {
			return Msg.fail().add("fileInfo", "未查到生活");
		}
	}
	
	
	/**
	 * 添加生活函数,需要传入userid
	 * @param life
	 * @param result
	 * @return
	 */
	@RequestMapping(value="/lifeCRUD",method=RequestMethod.POST)
	@ResponseBody
	public Msg saveLife(@Valid Life life,BindingResult result){
		if (life==null||life.getUserid()==null) {
			return Msg.fail().add("failInfo", "用户ID不可为空");
		}
		if (result.hasErrors()) {
			Map<String, Object> map =new HashMap<String, Object>();
			List<FieldError> errors =result.getFieldErrors();
			for (FieldError fieldError : errors) {
				System.out.println("错误字段名"+fieldError.getField());
				System.out.println("错误信息"+fieldError.getDefaultMessage());
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			System.out.println("进入函数");
			return Msg.fail().add("errorFields", map).add("addStatus", "添加失败");
		}else {
			lifeServices.saveLife(life);
			return Msg.success().add("addStatus", "添加成功");
		}
	}
	
	/**
	 * 生活修改功能
	 * @param life
	 * @return
	 */
	@RequestMapping(value="/lifeCRUD/{lifeid}",method=RequestMethod.PUT)
	@ResponseBody
	public Msg updateLife(Life life){
		lifeServices.updateLife(life);
		return Msg.success();
	}
	
	
	/**
	 * 生活删除功能
	 * @param lifeid
	 * @return
	 */
	@RequestMapping(value="/lifeCRUD/{lifeid}",method=RequestMethod.DELETE)
	@ResponseBody
	public Msg deleteByLifeId(@PathVariable("lifeid")Integer lifeId){
		lifeServices.deleteByLifeId(lifeId);
		return Msg.success();
	}
}
